package com.kexio.user.controller;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.kexio.auth.annotation.RequiresPermission;
import com.kexio.auth.context.TenantContextHolder;
import com.kexio.common.dto.Result;
import com.kexio.user.entity.Dept;
import com.kexio.user.service.DeptService;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;

/**
 * 部门管理控制器
 * 
 * @author Kexio Team
 * @since 1.0.0
 */
@Tag(name = "部门管理", description = "组织架构部门管理相关接口")
@RestController
@RequestMapping("/system/dept")
public class DeptController {

    @Autowired
    private DeptService deptService;

    /**
     * 获取组织架构树
     */
    @Operation(summary = "获取组织架构树", description = "获取当前租户的部门树形结构")
    @GetMapping("/tree")
    @RequiresPermission("system:dept:list")
    public Result<List<Dept>> getOrgTree() {
        List<Dept> deptTree = deptService.getDeptTree();
        return Result.success(deptTree);
    }

    /**
     * 获取部门详情
     */
    @Operation(summary = "获取部门详情", description = "根据部门ID获取部门详细信息")
    @GetMapping("/info/{deptId}")
    @RequiresPermission("system:dept:query")
    public Result<Dept> getDeptInfo(
            @Parameter(description = "部门ID") @PathVariable String deptId) {
        Dept dept = deptService.getDeptDetailById(deptId);
        if (dept == null) {
            return Result.error("部门不存在");
        }
        return Result.success(dept);
    }

    /**
     * 获取部门成员列表
     */
    @Operation(summary = "获取部门成员列表", description = "获取指定部门的成员列表")
    @GetMapping("/members/{deptId}")
    @RequiresPermission("system:dept:query")
    public Result<Map<String, Object>> getDeptMembers(
            @Parameter(description = "部门ID") @PathVariable String deptId,
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") int page,
            @Parameter(description = "页大小") @RequestParam(defaultValue = "10") int pageSize,
            @Parameter(description = "搜索关键词") @RequestParam(required = false) String keyword) {
        
        // 功能未开放：部门成员查询需要与UserService配合实现
        throw com.kexio.common.exception.BusinessException.operationNotAllowed(
            "部门成员查询功能暂未开放，请在用户管理模块按部门筛选查询"
        );
    }

    /**
     * 添加部门
     */
    @Operation(summary = "添加部门", description = "创建新的部门")
    @PostMapping("/add")
    @RequiresPermission("system:dept:add")
    public Result<Void> addDept(@Valid @RequestBody Dept dept) {
        // 验证部门编码唯一性
        if (dept.getDeptCode() != null && 
            !deptService.isCodeUnique(dept.getDeptCode(), TenantContextHolder.getCurrentTenantId(), null)) {
            return Result.error("部门编码已存在");
        }
        
        boolean success = deptService.saveDept(dept);
        if (success) {
            return Result.success("部门创建成功");
        } else {
            return Result.error("部门创建失败");
        }
    }

    /**
     * 更新部门
     */
    @Operation(summary = "更新部门", description = "更新部门信息")
    @PutMapping("/update")
    @RequiresPermission("system:dept:edit")
    public Result<Void> updateDept(@Valid @RequestBody Dept dept) {
        // 验证部门编码唯一性
        if (dept.getDeptCode() != null && 
            !deptService.isCodeUnique(dept.getDeptCode(), TenantContextHolder.getCurrentTenantId(), dept.getId())) {
            return Result.error("部门编码已存在");
        }
        
        boolean success = deptService.updateDept(dept);
        if (success) {
            return Result.success("部门更新成功");
        } else {
            return Result.error("部门更新失败");
        }
    }

    /**
     * 删除部门
     */
    @Operation(summary = "删除部门", description = "删除指定部门")
    @DeleteMapping("/delete/{deptId}")
    @RequiresPermission("system:dept:remove")
    public Result<Void> deleteDept(
            @Parameter(description = "部门ID") @PathVariable String deptId) {
        boolean success = deptService.deleteDept(deptId);
        if (success) {
            return Result.success("部门删除成功");
        } else {
            return Result.error("部门删除失败");
        }
    }

    /**
     * 移动部门位置
     */
    @Operation(summary = "移动部门", description = "移动部门到新的父部门下")
    @PutMapping("/move")
    @RequiresPermission("system:dept:edit")
    public Result<Void> moveDept(@RequestBody Map<String, Object> params) {
        String deptId = (String) params.get("deptId");
        String parentId = (String) params.get("parentId");
        Integer targetOrder = (Integer) params.get("targetOrder");
        
        boolean success = deptService.moveDept(deptId, parentId, targetOrder);
        if (success) {
            return Result.success("部门移动成功");
        } else {
            return Result.error("部门移动失败");
        }
    }

    /**
     * 获取可选父部门列表
     */
    @Operation(summary = "获取可选父部门", description = "获取可作为父部门的部门列表")
    @GetMapping("/available-parents")
    @RequiresPermission("system:dept:list")
    public Result<List<Dept>> getAvailableParentDepts(
            @Parameter(description = "排除的部门ID") @RequestParam(required = false) String deptId) {
        String tenantId = TenantContextHolder.getCurrentTenantId();
        List<Dept> availableParents = deptService.getAvailableParentDepts(deptId, tenantId);
        return Result.success(availableParents);
    }

    /**
     * 获取部门统计信息
     */
    @Operation(summary = "获取部门统计", description = "获取部门统计信息")
    @GetMapping("/statistics")
    @RequiresPermission("system:dept:list")
    public Result<Map<String, Object>> getOrgStatistics() {
        String tenantId = TenantContextHolder.getCurrentTenantId();
        Map<String, Object> statistics = deptService.getDeptStatistics(tenantId);
        return Result.success(statistics);
    }

    /**
     * 校验部门编码唯一性
     */
    @Operation(summary = "校验部门编码", description = "校验部门编码是否唯一")
    @GetMapping("/check-code")
    @RequiresPermission("system:dept:query")
    public Result<Boolean> checkDeptCode(
            @Parameter(description = "部门编码") @RequestParam String deptCode,
            @Parameter(description = "排除的部门ID") @RequestParam(required = false) String excludeId) {
        String tenantId = TenantContextHolder.getCurrentTenantId();
        boolean isUnique = deptService.isCodeUnique(deptCode, tenantId, excludeId);
        return Result.success(isUnique);
    }

    /**
     * 检查部门是否可删除
     */
    @Operation(summary = "检查删除权限", description = "检查部门是否可以删除")
    @GetMapping("/can-delete/{deptId}")
    @RequiresPermission("system:dept:query")
    public Result<Boolean> canDeleteDept(
            @Parameter(description = "部门ID") @PathVariable String deptId) {
        boolean canDelete = deptService.canDelete(deptId);
        return Result.success(canDelete);
    }

    // ==================== 扩展功能API ====================

    /**
     * 导出部门数据
     */
    @Operation(summary = "导出部门数据", description = "导出部门组织架构数据到Excel")
    @GetMapping("/export")
    @RequiresPermission("system:dept:export")
    public Result<String> exportDept(
            @Parameter(description = "部门ID，为空时导出全部") @RequestParam(required = false) String deptId) {
        // 功能未开放：部门导出需要实现Excel生成逻辑
        throw com.kexio.common.exception.BusinessException.operationNotAllowed(
            "部门导出功能暂未开放"
        );
    }

    /**
     * 导入部门数据
     */
    @Operation(summary = "导入部门数据", description = "从Excel导入部门组织架构数据")
    @PostMapping("/import")
    @RequiresPermission("system:dept:import")
    public Result<String> importDept(
            @Parameter(description = "导入文件") @RequestParam("file") org.springframework.web.multipart.MultipartFile file) {
        // 功能未开放：部门导入需要实现Excel解析和数据验证逻辑
        throw com.kexio.common.exception.BusinessException.operationNotAllowed(
            "部门导入功能暂未开放"
        );
    }

    /**
     * 添加部门成员
     */
    @Operation(summary = "添加部门成员", description = "将用户添加到指定部门")
    @PostMapping("/member/add")
    @RequiresPermission("system:dept:member:add")
    public Result<String> addDeptMember(@Valid @RequestBody DeptMemberRequest request) {
        // 功能未开放：添加部门成员需要与UserService配合实现
        // 替代方案：在用户管理模块编辑用户时修改所属部门
        throw com.kexio.common.exception.BusinessException.operationNotAllowed(
            "添加部门成员功能暂未开放，请在用户管理模块修改用户所属部门"
        );
    }

    /**
     * 移除部门成员
     */
    @Operation(summary = "移除部门成员", description = "从部门中移除指定用户")
    @DeleteMapping("/member/remove/{deptId}/{userId}")
    @RequiresPermission("system:dept:member:remove")
    public Result<String> removeDeptMember(
            @Parameter(description = "部门ID") @PathVariable String deptId,
            @Parameter(description = "用户ID") @PathVariable String userId) {
        // 功能未开放：移除部门成员需要与UserService配合实现
        // 替代方案：在用户管理模块编辑用户时修改所属部门
        throw com.kexio.common.exception.BusinessException.operationNotAllowed(
            "移除部门成员功能暂未开放，请在用户管理模块修改用户所属部门"
        );
    }

    /**
     * 批量转移部门成员
     */
    @Operation(summary = "批量转移部门成员", description = "将多个用户从一个部门批量转移到另一个部门")
    @PutMapping("/member/batch-move")
    @RequiresPermission("system:dept:member:move")
    public Result<String> batchMoveDeptMembers(@Valid @RequestBody BatchMoveMembersRequest request) {
        // 功能未开放：批量转移部门成员需要与UserService配合实现
        // 替代方案：在用户管理模块批量编辑用户时修改所属部门
        throw com.kexio.common.exception.BusinessException.operationNotAllowed(
            "批量转移部门成员功能暂未开放，请在用户管理模块批量修改用户所属部门"
        );
    }

    // ==================== 内部数据类 ====================
    
    public static class DeptMemberRequest {
        private String deptId;
        private String userId;
        private String position;
        
        public String getDeptId() { return deptId; }
        public void setDeptId(String deptId) { this.deptId = deptId; }
        public String getUserId() { return userId; }
        public void setUserId(String userId) { this.userId = userId; }
        public String getPosition() { return position; }
        public void setPosition(String position) { this.position = position; }
    }
    
    public static class BatchMoveMembersRequest {
        private String fromDeptId;
        private String toDeptId;
        private java.util.List<String> userIds;
        
        public String getFromDeptId() { return fromDeptId; }
        public void setFromDeptId(String fromDeptId) { this.fromDeptId = fromDeptId; }
        public String getToDeptId() { return toDeptId; }
        public void setToDeptId(String toDeptId) { this.toDeptId = toDeptId; }
        public java.util.List<String> getUserIds() { return userIds; }
        public void setUserIds(java.util.List<String> userIds) { this.userIds = userIds; }
    }
}